#include "config.h"
#include "pool.h"

#include <pqxx/pqxx>

#include <pthread.h>

using namespace PGSTD;
using namespace pqxx;

#define MAXN 64

ConnectionPool* my_pool;

void* thread_func(void* data) {
    connection* conn = (connection*) data;

    work my_work(*conn, "");
    result my_res = my_work.exec("SELECT * FROM tree;");
        
    for(result::const_iterator it = my_res.begin(); it != my_res.end(); it++)
    {
            result::field my_field = it["name"];
            string tmp;
            my_field.to(tmp);
            printf("%s\n", tmp.c_str());
    }
    
    my_work.commit();

    my_pool->put_connection(conn);
    return 0;
}

int main(void) {
    Config cfg;
    //cfg.host = "localhost";
    cfg.user = "postgrefs";
    cfg.password = "postgrefs";
    cfg.database = "postgrefs";
    cfg.port = "5432";
    cfg.init_conn_pool = 2;
    cfg.max_conn_pool = 4;

    pthread_t thread_id[MAXN];
    

    try {
        my_pool = new ConnectionPool(cfg);

        for(int i=0; i<MAXN; ++i) {
          connection* conn = my_pool->get_connection();
          pthread_create( &thread_id[i], NULL, thread_func, (void*) conn);

        }        

        delete my_pool;
    
    } catch(const broken_connection& e) {
       printf("Can not create connection\n");
    }



    return 0;
}

